package celiasoft.itasalib.filegatherer;

import java.io.ByteArrayInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.util.Log;
import celiasoft.itasalib.filegatherer.cache.FileCache;

public class ImageGatherer {

	private final static String TAG = "itasalib.ImageGatherer";
	
	private FileCache _cache;

	public ImageGatherer(FileCache cache) {
		this._cache = cache;
	}

	private String getFilePath(String url) {
		
		String filePath = this._cache.lookup(url);
		
		if (filePath == null) {
			
			try{
				URL remoteUrl = new URL(url);
				byte[] stream = FileHTTPFetcher.fetch(remoteUrl);

				if(stream != null){
					filePath = this._cache.cache(url, createBitmap(stream));
				}else{
					Log.d(TAG, "stream = null!");
				}
			}catch(IOException ex){
				ex.printStackTrace();
				Log.e(TAG, "Exception occurred during " + url + " file fetching.");
			}
		} 

		return filePath;

	}

	
	private Bitmap createBitmap(byte[] rawData) {
		ByteArrayInputStream stream = new ByteArrayInputStream(rawData);
		BitmapDrawable drawable = (BitmapDrawable) BitmapDrawable.createFromStream(stream, null);
		
		return drawable.getBitmap();
			
	}

	public final Bitmap getBitmap(String url){
		
		String filePath  = getFilePath(url);
		
		if(filePath == null){
			Log.d(TAG, "file fetching error");
			return null;
		}
		
		return BitmapFactory.decodeFile(filePath);
	}
	
	public final Document getXMLDocument(String url) {
		Document doc = null;

		String filePath  = getFilePath(url);
		
		if(filePath == null){
			Log.d(TAG, "file fetching error");
			return null;
		}
				
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		try {

			DocumentBuilder db = dbf.newDocumentBuilder();

			InputSource is = new InputSource();
			is.setCharacterStream(new FileReader(filePath));
			doc = db.parse(is);

		} catch (ParserConfigurationException e) {
			System.out.println("XML parse error: " + e.getMessage());
			return null;
		} catch (SAXException e) {
			System.out.println("Wrong XML file structure: " + e.getMessage());
			return null;
		} catch (IOException e) {
			System.out.println("I/O exception: " + e.getMessage());
			return null;
		}

		return doc;

	}

}
